package com.gitee.huanminabc.fastboot;

import com.gitee.huanminabc.fastboot.context.AppContext;
import com.gitee.huanminabc.fastboot.load.classload.AopClassLoad;
import com.gitee.huanminabc.fastboot.load.classload.AppContainerInitClassLoad;
import com.gitee.huanminabc.fastboot.load.classload.AppListenerClassLoad;
import com.gitee.huanminabc.fastboot.load.config.AppSystemConfigLoad;
import com.gitee.huanminabc.fastboot.load.hook.AppLoadFinishLifecycleHook;
import com.gitee.huanminabc.fastboot.load.hook.AppStartHookLifecycleHook;
import com.gitee.huanminabc.fastboot.load.hook.AppStopHookLifecycleHook;
import com.gitee.huanminabc.fastboot.load.metainfo.ScanMetaInfoFactories;
import com.gitee.huanminabc.fastboot.load.metainfo.ScanMetaInfoModule;
import com.gitee.huanminabc.fastboot.load.stage.AppLoadStageFactory;
import com.gitee.huanminabc.fastboot.logback.LogTraceContextHolder;
import com.gitee.huanminabc.nullchain.common.NullResult;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FastBoot {
    public static void run(Class<?> runClass) {
        init(runClass);
        //启动钩子
        new AppStartHookLifecycleHook().run();
        //程序退出时的钩子
        Runtime.getRuntime().addShutdownHook(new Thread(() -> new AppStopHookLifecycleHook().run()));

        try {
            AppSystemConfigLoad.start();
            //加载各种阶段的处理器
            AppLoadStageFactory.start();
        } catch (Exception e) {
            log.error("项目启动异常: ", e);
            System.exit(1);
        }
    }

    private static void init(Class<?> runClass) {

        //获取加载的模块
        ScanMetaInfoModule.load();


        //加载扩展配置
        ScanMetaInfoFactories.load();

        AppContext.taskTimeWatch.setTaskGroupNameDesc("各阶段时间仅供参考(因为是并发执行的)");
        AppContext.mainClass = runClass;
        //设置链路id的获取方法
        NullResult.TRACE_ID_FUN = LogTraceContextHolder::get;

        AppContext.classLoadIntercepts.add(new AopClassLoad());
        AppContext.classLoadIntercepts.add(new AppListenerClassLoad());
        AppContext.classLoadIntercepts.add(new AppContainerInitClassLoad());

        //加载完毕后清理资源
        AppLoadFinishLifecycleHook.appLoadFinishHooks.add(() -> {
            AppContext.allClasses.clear();
            AppContext.allAopInterceptorHandleClasses.clear();
            AppContext.allControllerClasses.clear();
            AppContext.containerInitMethods.clear();
            System.gc();//让gc来一次
        });

    }

}